package admin.service.impl;

import admin.bean.Express;
import admin.dao.ExpressDao;
import admin.dao.impl.ExpressDaoImpl;
import exception.ReCodeException;
import admin.service.ExpressService;

import java.util.List;
import java.util.Map;

public class ExpressServiceImpl implements ExpressService {

    ExpressDao dao = new ExpressDaoImpl();

    @Override
    public List<Map<String, Integer>> console() {
        return dao.console();
    }

    @Override
    public List<Express> findAll(boolean limit, int offset, int pageNumber) {
        return dao.findAll(limit, offset, pageNumber);
    }

    @Override
    public Express findByNumber(String number) {
        return dao.findByNumber(number);
    }

    @Override
    public Express findByCode(String code) {
        return dao.findByCode(code);
    }

    @Override
    public List<Express> findByUserPhone(String userPhone) {
        return dao.findByUserPhone(userPhone);
    }

    @Override
    public List<Express> findBySysPhone(String sysPhone) {
        return dao.findBySysPhone(sysPhone);
    }

    @Override
    public boolean insert(Express express) throws ReCodeException {
        try {
            boolean flag = dao.insert(express);
            if (flag){
                System.out.println("生成的取件码为："+express.getCode());
                //暂时未集成短信发送
            }
            return flag;
        } catch (ReCodeException e) {
            //取件码生成失败，产生异常后，回调方法重新生成取件码
            System.out.println("新增快递失败,生成取件码不成功");
            return insert(express);
        }
    }

    @Override
    public boolean update(int id, Express newExpress) throws ReCodeException {

        boolean flag = dao.update(id, newExpress);
        if (flag){
            //更新成功时,如果快递状态变为1即已取件，则将取件码设为null，并计入取出时间
            if (newExpress.getStatus()==1){
                Express e = findByNumber(newExpress.getNumber());
                String c = e.getCode();
                //则将取件码设为null，并计入取出时间
                boolean b = updateStatus(c);
                if (b){
                    System.out.println("取件码已清空");
                }

                return true;
            }
        }

        return flag;
    }

    @Override
    public boolean updateStatus(String code) {
        return dao.updateStatus(code);
    }

    @Override
    public boolean delete(int id) {
        return dao.delete(id);
    }
}
